#define _CRT_SECURE_NO_WARNINGS 1
int minFallingPathSum(int** matrix, int matrixSize, int* matrixColSize) {
    int m = matrixSize, n = *matrixColSize;
    if (n == 1)
    {
        int sum = 0;
        for (int i = 0; i < m; i++)
            sum += matrix[i][0];
        return sum;
    }
    if (m == 1)
    {
        int min = matrix[0][0];
        for (int j = 0; j < n; j++)
        {
            min = matrix[0][j] < min ? matrix[0][j] : min;
        }
        return min;
    }

    int dp[m][n];
    for (int j = 0; j < n; j++)
    {
        dp[0][j] = matrix[0][j];
    }

    for (int i = 1; i < m; i++)
    {

        for (int j = 0; j < n; j++)
            if (j == 0)
                dp[i][j] = (dp[i - 1][j] > dp[i - 1][j + 1] ? dp[i - 1][j + 1] : dp[i - 1][j]) + matrix[i][j];
            else if (j == n - 1)
                dp[i][j] = (dp[i - 1][j] > dp[i - 1][j - 1] ? dp[i - 1][j - 1] : dp[i - 1][j]) + matrix[i][j];
            else
                dp[i][j] = (dp[i - 1][j - 1] < dp[i - 1][j] ? (dp[i - 1][j - 1] < dp[i - 1][j + 1] ? dp[i - 1][j - 1] : dp[i - 1][j + 1]) : (dp[i - 1][j] < dp[i - 1][j + 1] ? dp[i - 1][j] : dp[i - 1][j + 1])) + matrix[i][j];
    }
    int min1 = dp[m - 1][0];
    for (int j = 0; j < n; j++)
    {
        min1 = dp[m - 1][j] < min1 ? dp[m - 1][j] : min1;
    }
    return min1;
}